package com.linkoog.devtools.intellij.ui.table.cell_editor;

import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.util.EventObject;

public class JComboBoxTableCellEditor extends AbstractDelegateTableCellEditor {

    public JComboBoxTableCellEditor(){
        this(new JComboBox());
    }

    public JComboBoxTableCellEditor(@NotNull JComboBox comboBox) {
        comboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
        delegate = new EditorDelegate() {
            public void setValue(Object value) {
                comboBox.setSelectedItem(value);
            }

            public Object getCellEditorValue() {
                return comboBox.getSelectedItem();
            }

            public boolean shouldSelectCell(EventObject anEvent) {
                if (anEvent instanceof MouseEvent) {
                    MouseEvent e = (MouseEvent) anEvent;
                    return e.getID() != MouseEvent.MOUSE_DRAGGED;
                }
                return true;
            }

            public boolean stopCellEditing() {
                if (comboBox.isEditable()) {
                    // Commit edited value.
                    comboBox.actionPerformed(new ActionEvent(JComboBoxTableCellEditor.this, 0, ""));
                }
                return super.stopCellEditing();
            }
        };
        comboBox.addActionListener(delegate);
        editorComponent = comboBox;
    }

    @Override
    public JComboBox getComponent() {
        return (JComboBox) editorComponent;
    }

}
